package org.zero.dao;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class ConfigOperator {
	private static File configFile;
	private static Properties configurationItems = new Properties();

	static {
		// 获取文件
		configFile = new File(ConfigOperator.class.getResource("config.properties").getFile().replace("%20", " "));

		// 加载文件内容
		try (FileInputStream fileInputStream = new FileInputStream(configFile)) {
			configurationItems.load(fileInputStream);
		} catch (FileNotFoundException e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null,
					"未找到config.properties文件\n" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE));
		} catch (IOException e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null,
					"读取config.properties文件出错\n" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE));
		}
	}

	public static int getPort() {
		try {
			return Integer.parseInt(configurationItems.getProperty("port", "8888"));
		} catch (Exception e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null,
					"解析配置项【port】出错，已自动设置为8888\n" + e.getMessage(), "警告", JOptionPane.WARNING_MESSAGE));
			return 8888;
		}
	}

	public static String getFilePath() {
		try {
			return configurationItems.getProperty("file", "/src/org/zero/dao/user.dat");
		} catch (Exception e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null,
					"获取配置项【file】出错，已自动设置为系统默认\n" + e.getMessage(), "警告", JOptionPane.WARNING_MESSAGE));
			return "/src/org/zero/dao/user.dat";
		}

	}

	public static String getServiceClass(String serviceName) {
		try {
			return configurationItems.getProperty(serviceName, "exit");
		} catch (Exception e) {
			SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(null,
					"获取配置项【" + serviceName + "】出错，已自动设置为 Exit\n" + e.getMessage(), "警告", JOptionPane.WARNING_MESSAGE));
			return "org.zero.service.ExitService";
		}
	}
}
